package com.jsh.erp.service.userCategory;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.*;
import com.jsh.erp.datasource.entities.User;
import com.jsh.erp.datasource.mappers.SupplierMapperEx;
import com.jsh.erp.datasource.mappers.UserCategoryMapper;
import com.jsh.erp.datasource.mappers.UserCategoryMapperEx;
import com.jsh.erp.datasource.mappers.UserMapperEx;
import com.jsh.erp.datasource.vo.TreeNode;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.supplier.SupplierService;
import com.jsh.erp.service.systemConfig.SystemConfigService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.IdUtils;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserCategoryService {
    private Logger logger = LoggerFactory.getLogger(UserCategoryService.class);

    @Resource
    private UserCategoryMapper userCategoryMapper;
    @Resource
    private UserCategoryMapperEx userCategoryMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;
    @Resource
    private UserMapperEx userMapperEx;
    @Resource
    private SupplierService supplierService;
    @Resource
    private SupplierMapperEx supplierMapperEx;
    @Resource
    private SystemConfigService systemConfigService;

    public UserCategory getUserCategory(String id)throws Exception {
        UserCategory result=null;
        try{
            result=userCategoryMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    public List<UserCategory> getUserCategoryListByIds(String ids)throws Exception {
        List<String> idList = StringUtil.strToStringList(ids);
        List<UserCategory> list = new ArrayList<>();
        try{
            UserCategoryExample example = new UserCategoryExample();
            example.createCriteria().andIdIn(idList);
            list = userCategoryMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<UserCategory> getUserCategory()throws Exception {
        UserCategoryExample example = new UserCategoryExample();
        List<UserCategory> list=null;
        try{
            list=userCategoryMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<UserCategory> getAllList(String parentId)throws Exception {
        List<UserCategory> list=null;
        try{
            list = getMCList(parentId);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public List<UserCategory> getMCList(String parentId)throws Exception {
        List<UserCategory> res= new ArrayList<UserCategory>();
        List<UserCategory> list=null;
        UserCategoryExample example = new UserCategoryExample();
        example.createCriteria().andParentIdEqualTo(parentId).andIdNotEqualTo(null);
        example.setOrderByClause("id");
        list=userCategoryMapper.selectByExample(example);
        if(list!=null && list.size()>0) {
            res.addAll(list);
            for(UserCategory mc : list) {
                List<UserCategory> mcList = getMCList(mc.getId());
                if(mcList!=null && mcList.size()>0) {
                    res.addAll(mcList);
                }
            }
        }
        return res;
    }

    public List<UserCategory> select(String name, Integer parentId, int offset, int rows) throws Exception{
        List<UserCategory> list=null;
        try{
            list=userCategoryMapperEx.selectByConditionUserCategory(name, parentId, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list;
    }

    public Long countUserCategory(String name, Integer parentId) throws Exception{
        Long result=null;
        try{
            result=userCategoryMapperEx.countsByUserCategory(name, parentId);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertUserCategory(JSONObject obj, HttpServletRequest request)throws Exception {
        UserCategory userCategory = JSONObject.parseObject(obj.toJSONString(), UserCategory.class);
        userCategory.setCreateTime(new Date());
        userCategory.setUpdateTime(new Date());
        userCategory.setUploadFlag("0");
        int result=0;
        try{
            result=userCategoryMapper.insertSelective(userCategory);
            logService.insertLog("商品类型",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(userCategory.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateUserCategory(JSONObject obj, HttpServletRequest request) throws Exception{
        UserCategory userCategory = JSONObject.parseObject(obj.toJSONString(), UserCategory.class);
        userCategory.setUpdateTime(new Date());
        userCategory.setUploadFlag("0");
        int result=0;
        try{
            result=userCategoryMapper.updateByPrimaryKeySelective(userCategory);
            logService.insertLog("商品类型",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(userCategory.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteUserCategory(String id, HttpServletRequest request)throws Exception {
        return batchDeleteUserCategoryByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteUserCategory(String ids, HttpServletRequest request)throws Exception {
        return batchDeleteUserCategoryByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteUserCategoryByIds(String ids) throws Exception {
        int result=0;
        String [] idArray=ids.split(",");
        //校验产品表	jsh_user
        List<Supplier> supplierList=null;
        String lanCode = systemConfigService.getLanCode();
        try{
            supplierList= supplierMapperEx.getSupplierListByCategoryIds(idArray);
        }catch(Exception e){
            JshException.readFail(logger, e,lanCode);
        }
        if(supplierList!=null&&supplierList.size()>0){
            logger.error("异常码[{}],异常提示[{}],参数,CategoryIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,"zh".equals(lanCode) ? ExceptionConstants.DELETE_FORCE_CONFIRM_MSG : ExceptionConstants.DELETE_FORCE_CONFIRM_MSG_US,ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    "zh".equals(lanCode) ? ExceptionConstants.DELETE_FORCE_CONFIRM_MSG : ExceptionConstants.DELETE_FORCE_CONFIRM_MSG_US);
        }
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<UserCategory> list = getUserCategoryListByIds(ids);
        for(UserCategory userCategory: list){
            sb.append("[").append(userCategory.getName()).append("]");
        }
        logService.insertLog("客户分类", sb.toString(),StringUtil.getRequest());
        //更新时间
        Date updateDate =new Date();
        //更新人
        User userInfo=userService.getCurrentUser();
        String updater=userInfo==null?null:userInfo.getId();
        String strArray[]=ids.split(",");
        if(strArray.length<1){
            return 0;
        }
        List<UserCategory> mcList = userCategoryMapperEx.getUserCategoryListByCategoryIds(idArray);
        if(mcList!=null && mcList.size()>0) {
            logger.error("异常码[{}],异常提示[{}]",
                    ExceptionConstants.MATERIAL_CATEGORY_CHILD_NOT_SUPPORT_DELETE_CODE,"zh".equals(lanCode) ? ExceptionConstants.MATERIAL_CATEGORY_CHILD_NOT_SUPPORT_DELETE_MSG:ExceptionConstants.MATERIAL_CATEGORY_CHILD_NOT_SUPPORT_DELETE_MSG_US);
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_CHILD_NOT_SUPPORT_DELETE_CODE,
                    "zh".equals(lanCode) ? ExceptionConstants.MATERIAL_CATEGORY_CHILD_NOT_SUPPORT_DELETE_MSG:ExceptionConstants.MATERIAL_CATEGORY_CHILD_NOT_SUPPORT_DELETE_MSG_US);
        } else {
            result=userCategoryMapperEx.batchDeleteUserCategoryByIds(updateDate,updater,strArray);
        }
        return result;
    }

     public int checkIsNameExist(String id, String name) throws Exception{
        UserCategoryExample example = new UserCategoryExample();
        example.createCriteria().andIdNotEqualTo(id).andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<UserCategory> list=null;
        try{
            list= userCategoryMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
        return list==null?0:list.size();
    }
    public boolean checkCategoryIdIsParents(String categoryId){
        boolean flag=false;
        UserCategoryExample example = new UserCategoryExample();
        example.createCriteria().andParentIdEqualTo(categoryId).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<UserCategory> userCategories = userCategoryMapper.selectByExample(example);
        if (userCategories!=null && userCategories.size()>0){
        }else {
            flag=true;
        }
        return flag;
    }

    public List<UserCategory> findById(String id)throws Exception {
        List<UserCategory> list=null;
        if(id!=null) {
            UserCategoryExample example = new UserCategoryExample();
            example.createCriteria().andIdEqualTo(id);
            try{
                list=userCategoryMapper.selectByExample(example);
            }catch(Exception e){
                JshException.readFail(logger, e, systemConfigService.getLanCode());
            }
        }
        return list;
    }
    /**
     * create by: cjl
     * description:
     *获取商品类别树数据
     * create time: 2019/2/19 14:30
     * @Param:
     * @return java.util.List<com.jsh.erp.datasource.vo.TreeNode>
     */
    public List<TreeNode> getUserCategoryTree(String id) throws Exception{
        List<TreeNode> list=null;
        try{
            list=userCategoryMapperEx.getNodeTree(id);
        }catch(Exception e){
            JshException.readFail(logger, e, systemConfigService.getLanCode());
        }
       return list;
    }
    /**
     * create by: cjl
     * description:
     *  新增商品类别信息
     * create time: 2019/2/19 16:30
     * @Param: mc
     * @return void
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int addUserCategory(UserCategory mc) throws Exception {
        logService.insertLog("商品类型",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(mc.getName()).toString(),
                StringUtil.getRequest());
        if(mc==null){
            return 0;
        }
        if(mc.getParentId()==null){
            //没有给定父级目录的id，默认设置父级目录为根目录的父目录
            mc.setParentId(BusinessConstants.MATERIAL_CATEGORY_ROOT_PARENT_ID);
        }
        //检查商品类型编号是否已存在
        checkUserCategorySerialNo(mc);
        //数据状态新增时默认设置为启用
        Date date=new Date();
        User userInfo=userService.getCurrentUser();
        //创建时间
        mc.setCreateTime(date);
        //更新时间
        mc.setUpdateTime(date);
        mc.setUploadFlag("0");
        int result=0;
        try{
            mc.setId(IdUtils.getUUID());
            result=userCategoryMapperEx.addUserCategory(mc);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int editUserCategory(UserCategory mc) throws Exception{
        logService.insertLog("商品类型",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(mc.getName()).toString(),
                StringUtil.getRequest());
        if(StringUtils.isEmpty(mc.getParentId())){
            //没有给定父级目录的id，默认设置父级目录为根目录的父目录
            mc.setParentId(BusinessConstants.MATERIAL_CATEGORY_ROOT_PARENT_ID);
        }
        //检查商品类型编号是否已存在
        checkUserCategorySerialNo(mc);
        //更新时间
        mc.setUpdateTime(new Date());
        //更新人
        User userInfo=userService.getCurrentUser();
        mc.setUploadFlag("0");
        int result=0;
        try{
            result= userCategoryMapperEx.editUserCategory(mc);
        }catch(Exception e){
            JshException.writeFail(logger, e, systemConfigService.getLanCode());
        }
        return result;
    }
    /**
     * 根据商品类别编号判断商品类别是否已存在
     * */
    public void  checkUserCategorySerialNo(UserCategory mc)throws Exception {
        if(mc==null){
            return;
        }
        if(StringUtil.isEmpty(mc.getSerialNo())){
            return;
        }
        //根据商品类别编号查询商品类别
        List<UserCategory> mList=null;
        String lanCode = systemConfigService.getLanCode();
        try{
            mList= userCategoryMapperEx.getUserCategoryBySerialNo(mc.getSerialNo(), mc.getId());
        }catch(Exception e){
            JshException.readFail(logger, e, lanCode);
        }
        if(mList==null||mList.size()<1){
            //未查询到对应数据，编号可用
            return;
        }
        if(mList.size()>1){
            //查询到的数据条数大于1，编号已存在
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_CODE,
                    "zh".equals(lanCode) ? ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_MSG:ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_MSG_US);
        }
        if(StringUtils.isEmpty(mc.getId())){
            //新增时，编号已存在
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_CODE,
                    "zh".equals(lanCode) ? ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_MSG:ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_MSG_US);
        }
        /**
         * 包装类型用equals来比较
         * */
        if(mc.getId().equals(mList.get(0).getId())){
            //修改时，相同编号，id不同
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_CODE,
                    "zh".equals(lanCode) ? ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_MSG:ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_MSG_US);
        }
    }

    /**
     * 根据名称获取类型
     * @param name
     */
    public String getCategoryIdByName(String name){
        String categoryId = null;
        UserCategoryExample example = new UserCategoryExample();
        example.createCriteria().andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<UserCategory> list = userCategoryMapper.selectByExample(example);
        if(list!=null && list.size()>0) {
            categoryId = list.get(0).getId();
        }
        return categoryId;
    }
}
